package com.wenhao.leetcode.medium;

/**
 * 题目：https://leetcode-cn.com/problems/set-matrix-zeroes/
 * 矩阵置零
 *
 * @author Wenhao Tong
 * @Description
 * @create 2021-07-01 18:46
 */
public class LeetCode73 {
    public static void main(String[] args) {

    }



    /**
     * 使用两个标记数组
     * @param matrix
     */
    public void setZeroes(int[][] matrix) {
        int[] row = new int[matrix.length];
        int[] column = new int[matrix[0].length];
        for (int i = 0;i < matrix.length;i++) {
            for (int j = 0;j < matrix[i].length;j++) {
                if (matrix[i][j] == 0) {
                    row[i] = 1;
                    column[j] = 1;
                }
            }
        }
        for (int i = 0;i < matrix.length;i++) {
            if (row[i] == 1) {
                for (int j = 0;j < matrix[i].length;j++) {
                    matrix[i][j] = 0;
                }
            }
        }
        for (int j = 0;j < matrix[0].length;j++) {
            if (column[j] == 1) {
                for (int i = 0;i < matrix.length;i++) {
                    matrix[i][j] = 0;
                }
            }
        }
    }

    /**
     * 使用第一行和第一列标记，额外使用两个数记录第一行和第一列的情况
     * @param matrix
     */
    public void setZeroes2(int[][] matrix) {
        int m = matrix.length, n = matrix[0].length;
        boolean flagCol0 = false, flagRow0 = false;
        for (int i = 0; i < m; i++) {
            if (matrix[i][0] == 0) {
                flagCol0 = true;
            }
        }
        for (int j = 0; j < n; j++) {
            if (matrix[0][j] == 0) {
                flagRow0 = true;
            }
        }
        for (int i = 1; i < m; i++) {
            for (int j = 1; j < n; j++) {
                if (matrix[i][j] == 0) {
                    matrix[i][0] = matrix[0][j] = 0;
                }
            }
        }
        for (int i = 1; i < m; i++) {
            for (int j = 1; j < n; j++) {
                if (matrix[i][0] == 0 || matrix[0][j] == 0) {
                    matrix[i][j] = 0;
                }
            }
        }
        if (flagCol0) {
            for (int i = 0; i < m; i++) {
                matrix[i][0] = 0;
            }
        }
        if (flagRow0) {
            for (int j = 0; j < n; j++) {
                matrix[0][j] = 0;
            }
        }
    }
}
